import wx
from pylab import *
import numpy
import functools
from avoscan.processing import split_by_scan

def angle_formatter(xmin, xmax, x, pos):
    
    scan_no = (x-xmin)//(xmax-xmin)
    
    if scan_no%2 ==0:
        #even scan number
        return int(x - (scan_no*(xmax-xmin)))
    else:
        #odd scan number
        return int(xmax - (x-(scan_no*xmax)))




if __name__ == '__main__':
    
    app = wx.PySimpleApp()
    
    file_to_plot = wx.FileSelector("Choose file to plot.")
    
    #try:
    angles = []
    angle_err = []
    column_amount = []
    column_amount_err = []
    
    with open(file_to_plot,"r") as ifp:
        #load values and errors from file
        for line in ifp:
            if line.startswith("#") or line.isspace() or line == "":
                continue            
            words = line.split()
            angles.append(float(words[2].lstrip().rstrip()))
            angle_err.append(float(words[3].lstrip().rstrip()))
            column_amount.append(float(words[4].lstrip().rstrip()))
            column_amount_err.append(float(words[5].lstrip().rstrip()))
    angles = numpy.array(angles)
    column_amount = numpy.array(column_amount)
    
    angle_max = numpy.max(angles)
    angle_min = numpy.min(angles)
    
    
    #TODO - fix the angle formatting on the x axis
    #f = functools.partial(angle_formatter, angle_min, angle_max)
    #ax = figure()
    
    #ax.gca().xaxis.set_major_formatter(FuncFormatter(f))
    
    
    i=0        
    for t in split_by_scan(angles, column_amount, column_amount_err, angle_err):
        if t[0][0]<t[0][-1]:
            plot(t[0]+(i*(angle_max-angle_min)),t[1],'-')
            #errorbar(t[0]+(i*(angle_max-angle_min)),t[1],t[2],t[3], label="scan "+str(i))
        else:
            plot((i*(angle_max-angle_min))+angle_min+(angle_max-t[0]),t[1],'-')
            #errorbar((i*(angle_max-angle_min))+angle_min+(angle_max-t[0]),t[1],t[2],t[3],label="scan "+str(i))
        i+=1
    ylabel("SO$_2$ Column Amount")
    xlabel("Scan Angle")
    show()
            
        
    #except Exception, e:
    #    wx.MessageBox(str(e.args[0]), "",wx.ICON_ERROR)
    #    raise e